/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.wizards;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import java.io.*;
import org.eclipse.ui.*;
import org.eclipse.ui.ide.IDE;

import es.upm.dit.gsi.eclipse.jadex.util.ImageFactory;

/**
 * Wizard for creating a new Agent
 *     
 * @author Pablo Muñoz
 * @TODO verify if the agent file exists in the current workspace
 */

public class AgentWizard extends Wizard implements INewWizard {
	private AgentWizardPage page;
	private ISelection selection;

	/**
	 * Constructor for Agent Wizard.
	 */
	public AgentWizard() {
		super();
		setNeedsProgressMonitor(true);
		setDefaultPageImageDescriptor(ImageFactory.getImageDescriptor(ImageFactory.GSI_BANNER_SMALL));
	}
	
	/**
	 * Adding the page to the wizard.
	 */
	public void addPages() {
		page = new AgentWizardPage(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		final IProject project = page.getSelectedProject();
		final String name = page.getAgentName();
		final String fileName = page.getFileName();
		final String _package = page.getAgentPackage();
		
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(name,_package, project, fileName, monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * The worker method. It will find the container, create the
	 * file if missing or just replace its contents, and open
	 * the editor on the newly created file.
	 */
	private void doFinish(
		String name,
		String _package,
		IProject project,
		String fileName,
		IProgressMonitor monitor)
		throws CoreException {		
		monitor.beginTask("Checking Package", 1);
		
		IFolder destination = createPackage(project, _package, monitor);
		
		monitor.worked(1);
		
		monitor.beginTask("Creating " + fileName, 2);
		final IFile file = destination.getFile(new Path(fileName));
		
		try {
			InputStream stream = openContentStream(name, _package);
			if (file.exists()) {
				file.setContents(stream, true, true, monitor);
			} else {
				file.create(stream, true, monitor);
			}
			stream.close();
		} catch (IOException e) {
		}
		monitor.worked(2);
		
		monitor.beginTask("Opening file for editing...", 3);
		getShell().getDisplay().asyncExec(new Runnable() {
			public void run() {
				IWorkbenchPage page =
					PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				try {
					IDE.openEditor(page, file, true);
				} catch (PartInitException e) {
				}
			}
		});
		monitor.worked(3);
	}
	
	/*
	 * This class generates the basic structure of the agent file 
	 */
	private InputStream openContentStream(String name, String _package) {			  
		String contents =
"<agent xmlns=\"http://jadex.sourceforge.net/jadex\"\n" +
"   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
"   xsi:schemaLocation=\"http://jadex.sourceforge.net/jadex\n" +
"                       http://jadex.sourceforge.net/jadex-2.0.xsd\" \n" +
"   name =\"" + name + "\"    package =\"" + _package + "\" >\n" + 
"    <imports/>\n" +
"    <capabilities/>\n" +
"    <beliefs/>\n" +
"    <goals/>\n" +
"    <plans/>\n" +
"    <events/>\n" +
"    <expressions/>\n" +
"    <properties/>\n" +
"    <configurations/>\n" +
"</agent>";
		return new ByteArrayInputStream(contents.getBytes());
	}


	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
	
	/*
	 * Private method for creating a new package for the agent
	 */
	private IFolder createPackage (IProject project, String packageName, IProgressMonitor monitor) throws CoreException{
		String[] fragments = packageName.split("\\.");
		IPath path = new Path("/src/");
		for(String f : fragments){
			path = path.append(f + "/");
			IFolder folder = project.getFolder(path);
			if(!folder.exists()){
				folder.create(false, true, monitor);
			}			
		}
		return project.getFolder(path);
	}
}